<?php

namespace App\Dao;

use App\Model\Closeness;
use App\Model\FollowList;
use App\Model\User;
use App\Utils\MemcacheClient;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;

class FollowListDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }


    /**
     * Note - 检查是否关注，$uid是否关注了$user_id
     * DateTime 2024/7/17 17:50
     * User Admin
     * @param $uid
     * @param $user_id
     * @return bool
     */
    public function checkIsFans($uid, $user_id)
    {
        $ret = $this->getIdolsCache($uid);
        if (empty($ret)) {
            return false;
        }
        return in_array($user_id, $ret);
    }


    /**
     * Note - $uid的偶像列表，我的关注列表
     * DateTime 2024/8/9 18:18
     * User Admin
     * @param $uid
     * @param $cache
     * @return array|mixed
     */
    public function getIdolsCache($uid, $cache = true)
    {
        $ret = MemcacheClient::getInstance()->get("user_idols_uids_" . $uid);
        if ($ret === false || !$cache) {
            $ret = array();
            $res = FollowList::query()->where('main_id', $uid)->get();
            if (!empty($res)) {
                foreach ($res as $v) {
                    $ret[] = $v['guest_id'];
                }
            }
            MemcacheClient::getInstance()->set("user_idols_uids_" . $uid, $ret, 300);
        }
        return $ret;
    }


    /**
     * 检测是否相互关注
     * @param $uid
     * @param $user_id
     * @return mixed
     */
    public function isMutual($uid, $user_id)
    {
        $total = FollowList::query()->where(function ($query) use ($uid, $user_id) {
            $query->where('main_id', $uid)->where('guest_id', $user_id);
        })->orWhere(function ($query) use ($uid, $user_id) {
            $query->where('main_id', $user_id)->where('guest_id', $uid);
        })->count();

        if ($total == 2) {
            return 1;
        }
        return 0;
    }


    /**
     * 是否关注对方
     * @param $uid
     * @param $user_id int 对方id
     * @return int
     */
    public function isConcern($uid, $user_id)
    {
        // $sql = "select * from tb_follow_list where main_id=? and guest_id=?";
        // $pd = $this->createCommand($sql);
        // $pd->execute([$uid,$user_id]);
        // $result = $pd->fetch(PDO::FETCH_ASSOC);
        $result = FollowList::query()->where('main_id', $uid)->where('guest_id', $user_id)->count();
        if (!empty($result)) {
            return 1;
        }
        return 0;
    }


    /**
     * Note - 分页取用户的访客列表
     * DateTime 2024/8/8 16:55
     * User Admin
     * @param $uid
     * @param $page
     * @param $pageSize
     * @return array
     */
    public function getVisitorsList($uid, $page = 1, $pageSize = 12)
    {
        $start = ($page - 1) * $pageSize;
        $data = User::query()->from('tb_user AS u')->rightJoin('tb_visit_list AS v', 'v.guest_id', 'u.id')
            ->select('u.id', 'u.nickname', 'u.head_image', 'u.signature', 'u.head_image_status', 'u.age', 'u.province', 'u.city', 'u.ext', 'u.noble', 'u.user_type', 'u.sex', 'u.level', 'v.time')
            ->where('v.guest_id', $uid)
            ->where('u.id', '>', 0)
            ->orderBy('v.time', 'DESC')
            ->skip($start)
            ->take($pageSize)
            ->get();

        return array('data' => $data->toArray());
    }


    /**
     * 我浏览过的用户
     * @param $uid
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getMyCheckUser($uid, int $page = 1, int $pageSize = 12)
    {
        $start = ($page - 1) * $pageSize;
        $data = User::query()->from('tb_user AS u')->rightJoin('tb_visit_list AS v', 'v.guest_id', 'u.id')
            ->select('u.id', 'u.nickname', 'u.head_image', 'u.signature', 'u.head_image_status', 'u.age', 'u.province', 'u.city', 'u.ext', 'u.noble', 'u.user_type', 'u.sex', 'u.level', 'v.time')
            ->where('v.main_id', $uid)
            ->where('u.id', '>', 0)
            ->orderBy('v.time', 'DESC')
            ->skip($start)
            ->take($pageSize)
            ->get();
        return array('data' => $data->toArray());
    }


    /**
     * Note - $uid 的粉丝数, 关注我的用户数，我的粉丝
     * DateTime 2024/8/8 19:18
     * User Admin
     * @param $uid
     * @return mixed
     */
    public function getUserFansNum($uid)
    {
        $total = MemcacheClient::getInstance()->get("user_fans_num_" . $uid);
        if ($total === false) {
            // $sql = "SELECT count(f.id) AS total FROM `".$this->tableF."` f left join tb_user u on f.main_id = u.id WHERE u.isdel=0 and guest_id = ?";
            // $pd = $this->createCommand($sql);
            // $pd->execute(array($uid));
            // $count = $pd->fetch(PDO::FETCH_ASSOC);
            // $total = $count['total'];
            $total = FollowList::query()->from('tb_follow_list as f')
                ->leftJoin('tb_user as u', 'u.id', '=', 'f.main_id')
                ->where('guest_id', $uid)->where('u.isdel', 0)->count();
            //加上一定基数(基数控制在100-500)
            /*$baseNum = (int)substr(sprintf('%u',crc32($uid)), 0, 3);
            $total = $total + ($baseNum>=200 ? ceil($baseNum/2) : $baseNum);*/
            MemcacheClient::getInstance()->set("user_fans_num_" . $uid, $total, 300);
        }
        return $total;
    }


    /**
     * Note - 我的粉丝列表(关注我的)
     * DateTime 2024/8/9 18:42
     * User Admin
     * @param $uid
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function getFansList($uid, $page = 1, $pagesize = 12)
    {
        $page = ($page - 1) * $pagesize;
        return FollowList::query()->from('tb_follow_list as f')
            ->leftJoin('tb_user as u', 'u.id', '=', 'f.main_id')
            ->where('guest_id', $uid)->where('u.isdel', 0)
            ->select('u.id', 'u.nickname', 'u.signature', 'u.age', 'u.ext', 'u.height', 'u.head_image', 'u.province', 'u.city', 'u.head_image_status', 'u.noble', 'u.user_type', 'u.sex', 'u.level')
            ->orderBy('f.id', 'DESC')->skip($page)->limit($pagesize)->get()->toArray();

    }


    /**
     * Note - 用户的偶像数量(我关注的)
     * DateTime 2024/8/8 19:18
     * User Admin
     * @param $uid
     * @return mixed
     */
    public function getUserFocusNum($uid)
    {

        $total = MemcacheClient::getInstance()->get("user_focus_num_" . $uid);
        if ($total === false) {
            $total = FollowList::query()->from('tb_follow_list as f')
                ->leftJoin('tb_user as u', 'u.id', '=', 'f.guest_id')
                ->where('main_id', $uid)->where('u.isdel', 0)->count();
            //加上一定基数(基数控制在100-500)
            /*$baseNum = (int)substr(sprintf('%u',crc32($uid)), 0, 3);
            $total = $total + ($baseNum>=200 ? ceil($baseNum/2) : $baseNum);*/
            MemcacheClient::getInstance()->set("user_focus_num_" . $uid, $total, 300);
        }

        return $total;
    }


    /**
     * Note - 用户的偶像列表(我关注的)
     * DateTime 2024/8/9 19:10
     * User Admin
     * @param $uid
     * @param int $page
     * @param int $pagesize
     * @return mixed
     */
    public function getIdolsList($uid, $page = 1, $pagesize = 12)
    {
        $page = ($page - 1) * $pagesize;
        return FollowList::query()->from('tb_follow_list as f')
            ->leftJoin('tb_user as u', 'u.id', '=', 'f.guest_id')
            ->where('main_id', $uid)->where('u.isdel', 0)
            ->select('u.id', 'u.nickname', 'u.signature', 'u.age', 'u.ext', 'u.height', 'u.head_image', 'u.province', 'u.city', 'u.head_image_status', 'u.noble', 'u.user_type', 'u.sex', 'u.level')
            ->orderBy('f.id', 'DESC')->skip($page)->limit($pagesize)->get()->toArray();
    }


    /**
     * Note - 与 $uid 互相关注的数量
     * DateTime 2024/8/8 19:19
     * User Admin
     * @param $uid
     * @return mixed
     */
    public function getMutualNum($uid)
    {
        $total = MemcacheClient::getInstance()->get("user_mutual_num_" . $uid);
        if ($total === false) {
            // $sql = "SELECT count(a.id) as total FROM `".$this->tableF."` a INNER JOIN `".$this->tableF."` b ON a.main_id = b.guest_id
            //     and b.main_id=a.guest_id inner join tb_user u on a.main_id=u.id inner join tb_user uu on b.main_id=uu.id WHERE u.isdel=0 and uu.isdel=0 and a.main_id = ?;";
            // $pd = $this->createCommand($sql);
            // $pd->execute(array($uid));
            // $count = $pd->fetch(PDO::FETCH_ASSOC);
            // $total = $count['total'];
            $total = FollowList::query()->from('tb_follow_list as f1')
                ->join('tb_follow_list as f2', function ($join) {
                    $join->on('f1.main_id', '=', 'f2.guest_id')->where('f1.guest_id', '=', Db::raw('f2.main_id'));
                })
                ->leftJoin('tb_user as u', 'f1.main_id', 'u.id')
                ->leftJoin('tb_user as uu', 'f2.main_id', 'uu.id')
                ->where('f1.main_id', $uid)
                ->where('u.isdel', 0)
                ->where('uu.isdel', 0)
                ->count();
            MemcacheClient::getInstance()->set("user_mutual_num_" . $uid, $total, 300);
        }
        return $total;
    }


    /**
     * 获取相互关注的用户列表
     * @param $uid
     * @param int $page
     * @param int $pagesize
     * @return mixed
     */
    public function getMutualList($uid, $page = 1, $pagesize = 12)
    {

        $page = ($page - 1) * $pagesize;
        return FollowList::query()->from('tb_follow_list as f1')
            ->join('tb_follow_list as f2', function ($join) {
                $join->on('f1.main_id', '=', 'f2.guest_id')->where('f1.guest_id', '=', Db::raw('f2.main_id'));
            })
            ->leftJoin('tb_user as u', 'f1.guest_id', 'u.id')
            ->leftJoin('tb_user as uu', 'f2.main_id', 'uu.id')
            ->where('f1.main_id', $uid)
            ->where('u.isdel', 0)
            ->where('uu.isdel', 0)
            ->select('u.id', 'u.nickname', 'u.signature', 'u.age', 'u.ext', 'u.height', 'u.head_image', 'u.province', 'u.city', 'u.head_image_status', 'u.noble', 'u.user_type', 'u.sex', 'u.level')
            ->orderBy('f1.id', 'DESC')->skip($page)->limit($pagesize)->get()->toArray();
    }


    /**
     * Note - 获取密友列表
     * DateTime 2024/8/9 19:26
     * User Admin
     * @param $uid
     * @param int $page
     * @param int $pagesize
     * @param int $sex
     * @return mixed
     */
    public function getClosenessList($uid, $page = 1, $pagesize = 12, $sex = 2)
    {
        $page = ($page - 1) * $pagesize;
        //女用户
        if ($sex == 2) {
            // $sql = "SELECT u.`id`, u.`nickname`,u.`age`,u.`ext`,u.height,u.`head_image`,u.`province`,u.`city`,u.`head_image_status`,u.`noble`,u.`user_type`,u.`online`,u.`sex`,u.`level`,u.`signature`,c.`score` closeness,c.`level` close_level,u.hide_call_status,u.register_time FROM `".$this->tableC."` c inner join `".$this->tableUser."` u ON c.uid = u.id WHERE u.isdel = ? and c.`score`>0 AND c.anchor_id = ? ".$order.$limit;
            return Closeness::query()->from('tb_closeness AS c')->join('tb_user AS u', 'c.uid', '=', 'u.id')
                ->where('u.isdel', 0)
                ->where('c.anchor_id', $uid)
                ->where('c.score', '>', 0)
                ->select('u.id', 'u.nickname', 'u.age', 'u.ext', 'u.height', 'u.head_image', 'u.province', 'u.city', 'u.head_image_status', 'u.noble', 'u.user_type', 'u.online', 'u.sex', 'u.level', 'u.signature', Db::raw('c.score AS closeness'), Db::raw('c.level AS close_level'), 'u.hide_call_status', 'u.register_time')
                ->orderBy('c.score', 'DESC')->skip($page)->limit($pagesize)->get()->toArray();
        } elseif ($sex == 1) {
            // $sql = "SELECT u.`id`, u.`nickname`,u.`age`,u.`ext`,u.height,u.`head_image`,u.`province`,u.`city`,u.`head_image_status`,u.`noble`,u.`user_type`,u.`online`,u.`sex`,u.`level`,u.`signature`,c.`score` closeness,c.`level` close_level,u.hide_call_status,u.register_time FROM `".$this->tableC."` c inner join `".$this->tableUser."` u ON c.anchor_id = u.id WHERE u.isdel = ? and c.`score`>0 AND c.uid = ? ".$order.$limit;
            return Closeness::query()->from('tb_closeness AS c')->join('tb_user AS u', 'c.anchor_id', '=', 'u.id')
                ->where('u.isdel', 0)
                ->where('c.uid', $uid)
                ->where('c.score', '>', 0)
                ->select('u.id', 'u.nickname', 'u.age', 'u.ext', 'u.height', 'u.head_image', 'u.province', 'u.city', 'u.head_image_status', 'u.noble', 'u.user_type', 'u.online', 'u.sex', 'u.level', 'u.signature', Db::raw('c.score AS closeness'), Db::raw('c.level AS close_level'), 'u.hide_call_status', 'u.register_time')
                ->orderBy('c.score', 'DESC')->skip($page)->limit($pagesize)->get()->toArray();
        }

    }


    /**
     * Note - 关注 $uid 关注 $user_id
     * DateTime 2024/8/12 18:53
     * User Admin
     * @param $uid
     * @param $user_id
     */
    public function concern($uid, $user_id)
    {
        FollowList::query()->updateOrInsert(['main_id' => $uid, 'guest_id' => $user_id], ['main_id' => $uid, 'guest_id' => $user_id, 'time' => time()]);
    }


    /**
     * Note - 取消关注，删除已关注的记录
     * DateTime 2024/8/12 19:11
     * User Admin
     * @param $uid
     * @param $user_id
     */
    public function cancel($uid, $user_id)
    {

        // $sql = "DELETE FROM `".$this->tableF."` WHERE main_id = ? AND guest_id = ? LIMIT 1";
        // $pd = $this->createCommand($sql);
        // $pd->execute(array($uid,$user_id));
        FollowList::query()->where('main_id', $uid)->where('guest_id', $user_id)->delete();

    }


}